package com.qf.springboottest.interceptor;

import com.qf.springboottest.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 拦截器
 * */

@Component
@Slf4j
//实现 HandlerInterceptor
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //打印日志   取url地址 request.getRequestURI()
        log.debug("请求进入拦截器了,请求的url={}",request.getRequestURI());

        //判断用户的登录状态, 约定,如果session中有key user,并且value不为null,代表该浏览器曾经登录
        //先拿session对象
        HttpSession session = request.getSession();
        Object user = session.getAttribute(Constants.User_LOGIN_SESSION_KEY);

        if (user != null){
            //登录过,放行
            log.debug("请求被放行了");
            return true;
        }
        log.debug("请求被拦截了,重定向到登录页");
        //让浏览器重定向到登录页 /login.html
        response.sendRedirect("login.html");

        return false;
    }
}


















